package com.dkd.http.controller;

import cn.elegent.iu.annotation.ElegentIU;
import cn.elegent.pay.ElegentPay;
import cn.elegent.pay.dto.PayRequest;
import cn.elegent.pay.dto.PayResponse;
import com.dkd.entity.OrderEntity;
import com.dkd.service.ESOrderService;
import com.dkd.service.OrderService;
import com.dkd.vo.OrderVO;
import com.dkd.vo.Pager;
import com.dkd.vo.PayVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ElegentPay elegentPay;

    @Autowired
    private ESOrderService esOrderService;

    /**
     * 请求支付
     *
     * @param payVO     支付签证官
     * @param tradeType 贸易类型
     * @param playform  playform
     * @return {@link PayResponse }
     * @author DiXiaoNie
     * @date 2023/02/04
     */
    @ElegentIU
    @PostMapping("/requestPay/{tradeType}/{platform}")
    public PayResponse requestPay(@RequestBody PayVO payVO, @PathVariable("tradeType") String tradeType, @PathVariable("platform") String playform) {
        //创建订单
        OrderEntity orderEntity = this.orderService.createOrder(payVO, playform);
        //封装支付请求对象调用支付
        PayRequest payRequest = new PayRequest();
        //商品名称
        payRequest.setBody(orderEntity.getSkuName());
        //订单编号
        payRequest.setOrderSn(orderEntity.getOrderNo());
        //订单金额
        payRequest.setTotalFee(orderEntity.getAmount().intValue());
        //openid
        payRequest.setOpenid(payVO.getOpenId());
        return this.elegentPay.requestPay(payRequest, tradeType, playform);
    }

    @GetMapping("/openid/{jsCode}")
    public String getOpenid(@PathVariable("jsCode") String jsCode) {
        return elegentPay.getOpenid(jsCode, "wxpay");
    }


    @GetMapping("/search")
    public Pager<OrderVO> search(
            @RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "orderNo", required = false, defaultValue = "") String orderNo,
            @RequestParam(value = "openId", required = false, defaultValue = "") String openId,
            @RequestParam(value = "startDate", required = false, defaultValue = "") String startDate,
            @RequestParam(value = "endDate", required = false, defaultValue = "") String endDate) {

        return this.esOrderService.search(pageIndex, pageSize, orderNo, openId, startDate, endDate);
    }
}